#include "model.h"
#include <QDebug>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <QDir>
#include "resourcemanager.h"

Model::Model()
{
}

Model::~Model()
{
    for (int i = 0; i < meshes.size(); ++i)
    {
        delete meshes[i];
    }
}

GLboolean Model::loadModel(const QString &file, GLboolean gamma)
{
    gammaCorrection = gamma;

    Assimp::Importer importer;
    const aiScene *scene = importer.ReadFile(file.toStdString(),
                           aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
    if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
    {
        qDebug() << "ERROR::ASSIMP::" << importer.GetErrorString();
        return GL_FALSE;
    }

    // retrieve the directory path of the filepath
    QDir filePath(file);
    directory = filePath.dirName();

    // process ASSIMP's root node recursively
    processNode(scene->mRootNode, scene);

    return GL_TRUE;
}

void Model::processNode(aiNode *node, const aiScene *scene)
{
    // 处理节点所有的网格（如果有的话）
    for (unsigned int i = 0; i < node->mNumMeshes; ++i)
    {
        aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
        meshes.push_back(processMesh(mesh, scene));
    }

    // 接下来对它的子节点重复这一过程
    for (unsigned int i = 0; i < node->mNumChildren; ++i)
    {
        processNode(node->mChildren[i], scene);
    }
}

Mesh *Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
    Mesh *aMesh = new Mesh();
    if (nullptr == aMesh)
    {
        return nullptr;
    }

    Vertex vertex;

    vertex.position = QVector3D(0.5f,  0.5f, 0.0f);
    aMesh->vertices.push_back(vertex);

    vertex.position = QVector3D(0.5f, -0.5f, 0.0f);
    aMesh->vertices.push_back(vertex);

    vertex.position = QVector3D(-0.5f, -0.5f, 0.0f);
    aMesh->vertices.push_back(vertex);

    vertex.position = QVector3D(-0.5f,  0.5f, 0.0f);
    aMesh->vertices.push_back(vertex);

    aMesh->indices.push_back(0);
    aMesh->indices.push_back(1);
    aMesh->indices.push_back(2);
    aMesh->indices.push_back(1);
    aMesh->indices.push_back(2);
    aMesh->indices.push_back(3);

    if (!aMesh->init())
    {
        delete aMesh;
        return nullptr;
    }

    return aMesh;

    for (unsigned int i = 0; i < mesh->mNumVertices; ++i)
    {
        Vertex vertex;

        // 处理顶点位置、法线和纹理坐标
        QVector3D vec;
        vec.setX(mesh->mVertices[i].x);
        vec.setY(mesh->mVertices[i].y);
        vec.setZ(mesh->mVertices[i].z);
        vertex.position = vec;

//        vec.setX(mesh->mNormals[i].x);
//        vec.setY(mesh->mNormals[i].y);
//        vec.setZ(mesh->mNormals[i].z);
//        vertex.normal = vec;

        // Assimp允许一个模型在一个顶点上有最多8个不同的纹理坐标，我们这里只关心第一组纹理坐标
//        if (mesh->mTextureCoords[0]) // 网格是否有纹理坐标？
//        {
//            QVector2D vec;
//            vec.setX(mesh->mTextureCoords[0][i].x);
//            vec.setY(mesh->mTextureCoords[0][i].y);
//            vertex.texCoords = vec;
//        }
//        else
//        {
//            vertex.texCoords = QVector2D(0.0f, 0.0f);
//        }

        // 有的文件可能没有切线和双切线信息
//        // tangent 切线
//        vec.setX(mesh->mTangents[i].x);
//        vec.setY(mesh->mTangents[i].y);
//        vec.setZ(mesh->mTangents[i].z);
//        vertex.tangent = vec;

//        // bitangent 双切线
//        vec.setX(mesh->mBitangents[i].x);
//        vec.setY(mesh->mBitangents[i].y);
//        vec.setZ(mesh->mBitangents[i].z);
//        vertex.bitangent = vec;

        aMesh->vertices.push_back(vertex);
    }

    // 处理索引  now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
    for (unsigned int i = 0; i < mesh->mNumFaces; ++i)
    {
        aiFace face = mesh->mFaces[i];

        for (unsigned int j = 0; j < face.mNumIndices; ++j)
        {
            aMesh->indices.push_back(face.mIndices[j]);
        }
    }

    if (!aMesh->init())
    {
        delete aMesh;
        return nullptr;
    }

    return aMesh;
    // 处理材质
    // we assume a convention for sampler names in the shaders. Each diffuse texture should be named
    // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
    // Same applies to other texture as the following list summarizes:
    // diffuse: texture_diffuseN
    // specular: texture_specularN
    // normal: texture_normalN

    aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];

    // 1. diffuse maps
    QVector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
    for (QVector<Texture>::const_iterator iter = diffuseMaps.begin(); iter != diffuseMaps.end(); ++iter)
    {
        aMesh->textures.insert(aMesh->textures.end(), *iter);
    }

    // 2. specular maps
    QVector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
    for (QVector<Texture>::const_iterator iter = specularMaps.begin(); iter != specularMaps.end(); ++iter)
    {
        aMesh->textures.insert(aMesh->textures.end(), *iter);
    }

    // 3. normal maps
    QVector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal"); // todo 后面这两个是不是不对？
    for (QVector<Texture>::const_iterator iter = normalMaps.begin(); iter != normalMaps.end(); ++iter)
    {
        aMesh->textures.insert(aMesh->textures.end(), *iter);
    }

    // 4. height maps
    QVector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
    for (QVector<Texture>::const_iterator iter = heightMaps.begin(); iter != heightMaps.end(); ++iter)
    {
        aMesh->textures.insert(aMesh->textures.end(), *iter);
    }

    if (!aMesh->init())
    {
        delete aMesh;
        return nullptr;
    }

    return aMesh;
}

QVector<Texture> Model::loadMaterialTextures(aiMaterial *mat, aiTextureType type, QString typeName)
{
    QVector<Texture> textures;

    for (unsigned int i = 0; i < mat->GetTextureCount(type); ++i)
    {
        aiString str;
        mat->GetTexture(type, i, &str);

        bool skip = false;

        for (int j = 0; j < texturesLoaded.size(); ++j)
        {
            if (0 == texturesLoaded[j].path.compare(str.C_Str()))
            {
                textures.push_back(texturesLoaded[j]);
                skip = true;
                break;
            }
        }

        if (!skip)
        {
            // 如果纹理还没有被加载，则加载它
            Texture2D *texture2d = ResourceManager::loadTexture(str.C_Str(), str.C_Str());

            Texture texture;
            texture.id = texture2d->textureID();
            texture.type = typeName;
            texture.path = str.C_Str();

            textures.push_back(texture);
            texturesLoaded.push_back(texture); // 添加到已加载的纹理中
        }
    }

    return textures;
}

void Model::draw()
{
    for (int i = 0; i < meshes.size(); ++i)
    {
        meshes[i]->draw();
    }
}
